<template>
  <div class="app-container">
    <!-- 头部过滤部分  -->
    <div class="filter-container">
      <el-input
        v-model="listQuery.search"
        placeholder="模糊搜索"
        style="width: 200px;"
        size="small"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      ><i slot="prefix" class="el-input__icon el-icon-search" /></el-input>
      <el-button
        v-if="checkPermission(['admin','role_create','role_all'])"
        class="filter-item"
        size="small"
        style="margin-left: 10px;"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >新增</el-button>
    </div>
    <!--表格渲染-->
    <div>
      <el-table
        v-if="checkPermission(['admin','role_list','role_all'])"
        :key="tableKey"
        v-loading="listLoading"
        :data="list"
        fit
        highlight-current-row
        size="small"
        border
        style="width: 100%;"
      >
        <el-table-column label="序号" width="60" prop="id" align="center" />
        <el-table-column label="名称" prop="name" />
        <el-table-column prop="desc" label="描述" />
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button v-if="checkPermission(['admin','role_edit','role_all'])" type="primary" size="mini" :disabled="scope.row.name === '超级管理员'" @click="handleUpdate(scope.row)">
              编辑
            </el-button>
            <el-button v-if="checkPermission(['admin','menu_edit','role_all'])" type="success" size="mini" :disabled="scope.row.name === '超级管理员'" @click="handleMenu(scope.row)">
              菜单
            </el-button>
            <el-button v-if="checkPermission(['admin','permission_edit','role_all'])" type="info" size="mini" :disabled="scope.row.name === '超级管理员'" @click="handlePer(scope.row)">
              权限
            </el-button>
            <el-button v-if="checkPermission(['admin','role_delete','role_all'])" slot="reference" :disabled="scope.row.id === 1" type="danger" size="mini" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!--分页组件-->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="500px">
      <el-form ref="dataForm" :rules="rules" :model="form" size="small" label-width="70px">
        <el-form-item label="角色名" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="描述" prop="desc">
          <el-input v-model="form.desc" rows="5" type="textarea" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">确认</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogMenuVisible" width="500px">
      <el-tree
        ref="menu"
        :data="menu_list"
        check-strictly
        show-checkbox
        accordion
        node-key="id"
        default-expand-all
        highlight-current
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogMenuVisible = false">取消</el-button>
        <el-button type="primary" @click="updateMenu()">保存</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogPerVisible" width="500px">
      <el-tree
        ref="permission"
        :data="permission_list"
        show-checkbox
        default-expand-all
        accordion
        node-key="id"
        highlight-current
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogPerVisible = false">取消</el-button>
        <el-button type="primary" @click="updatePermissions()">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from '@/components/Pagination'
import checkPermission from '@/utils/permission'
import { getRoles, delRole, editRole, addRole, editRolePatch } from '@/api/role'
import { getPermissionTree } from '@/api/permission'
import { getMenuTree } from '@/api/menu'
export default {
  components: { Pagination },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      rowId: 0,
      menu_list: [],
      permission_list: [],
      listQuery: {
        page: 1,
        limit: 10,
        search: undefined
      },
      span: 24,
      show: false,
      is_permissions: false,
      table_show: true,
      Loading: false,
      sup_this: this,
      form: {
        id: undefined,
        name: '',
        desc: ''
      },
      dialogMenuVisible: false,
      dialogFormVisible: false,
      dialogPerVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '新增',
        menu: '菜单分配',
        permission: '权限分配'
      },
      rules: {
        name: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getList()
    this.getPermissions()
    this.getMenus()
  },
  methods: {
    checkPermission,
    getList() {
      getRoles(this.listQuery).then(response => {
        this.list = response.results
        this.total = response.count
        this.listLoading = false
        // Just to simulate the time of the request
        // setTimeout(() => {
        //   this.listLoading = false
        // }, 170)
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    resetForm() {
      this.form = {
        id: undefined,
        name: '',
        desc: ''
      }
    },
    handleDelete(row) {
      this.$confirm('此操作将永久删除此行, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delRole(row.id).then(response => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          const index = this.list.indexOf(row)
          this.list.splice(index, 1)
          this.handleFilter()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    handleCreate() {
      this.resetForm()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          addRole(this.form).then(() => {
            this.resetForm()
            // this.list.unshift(this.temp)
            this.$message({
              type: 'success',
              message: '创建成功!'
            })
            this.dialogFormVisible = false
            this.getList()
          })
        }
      })
    },
    handleUpdate(row) {
      this.resetForm()
      this.form = { ...row }
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          editRole(this.form.id, this.form).then(() => {
            for (const v of this.list) {
              if (v.id === this.form.id) {
                const index = this.list.indexOf(v)
                this.list.splice(index, 1, this.form)
                break
              }
            }
            this.dialogFormVisible = false
            this.$message({
              type: 'success',
              message: '更新成功!'
            })
            this.getList()
          })
        }
      })
    },
    handlePer(row) {
      this.dialogStatus = 'permission'
      this.dialogPerVisible = true
      this.rowId = row.id
      this.$nextTick(() => {
        // 延迟赋值,等待DOM加载
        this.$refs.permission.setCheckedKeys(row.permissions)
      })
    },
    handleMenu(row) {
      this.dialogMenuVisible = true
      this.dialogStatus = 'menu'
      this.rowId = row.id
      this.$nextTick(() => {
        // 延迟赋值,等待DOM加载
        this.$refs.menu.setCheckedKeys(row.menus)
      })
    },
    updatePermissions() {
      const form = { permissions: this.$refs.permission.getCheckedKeys() }
      editRolePatch(this.rowId, form).then(res => {
        this.$message({
          type: 'success',
          message: '权限更新成功!'
        })
        this.dialogPerVisible = false
        this.handleFilter()
      })
    },
    updateMenu() {
      const form = { menus: this.$refs.menu.getCheckedKeys() }
      editRolePatch(this.rowId, form).then(res => {
        this.$message({
          type: 'success',
          message: '菜单更新成功!'
        })
        this.dialogMenuVisible = false
        this.handleFilter()
      })
    },
    getMenus() {
      if (Array.isArray(this.menu_list) && this.menu_list.length === 0) {
        getMenuTree().then(res => {
          this.menu_list = res.data
        })
      }
    },
    getPermissions() {
      if (Array.isArray(this.permission_list) && this.permission_list.length === 0) {
        getPermissionTree().then(res => {
          this.permission_list = res.data
        })
      }
    }

  }
}
</script>

